package com.newdjk.newdoctor.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.newdjk.newdoctor.MainActivity;
import com.newdjk.newdoctor.MyApplication;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.base.BaseAppcompatActivity;
import com.newdjk.newdoctor.entity.LoginEntity;
import com.newdjk.newdoctor.entity.PrescriptionMessageEntity;
import com.newdjk.newdoctor.net.BaseComPleteObserver;
import com.newdjk.newdoctor.net.NetServices;
import com.newdjk.newdoctor.utils.Contants;
import com.newdjk.newdoctor.utils.Event;
import com.newdjk.newdoctor.utils.LogUtils;
import com.newdjk.newdoctor.utils.MyCountDownTimer;
import com.newdjk.newdoctor.utils.RxBus;
import com.newdjk.newdoctor.utils.SpUtils;
import com.newdjk.newdoctor.utils.StrUtil;
import com.newdjk.newdoctor.utils.ToastUtil;
import com.newdjk.newdoctor.view.MyCheckBox;
import com.newdjk.okhttp.RetrofitFactory;
import com.newdjk.okhttp.entity.BaseEntity;
import com.newdjk.okhttp.entity.Login;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class LoginActivity extends BaseAppcompatActivity {


    private static final String TAG = "LoginActivity";
    @BindView(R.id.input_user)
    EditText inputUser;
    @BindView(R.id.input_password)
    EditText inputPassword;
    @BindView(R.id.CheckBox)
    MyCheckBox CheckBox;
    @BindView(R.id.tv_switch_login)
    TextView tvSwitchLogin;
    @BindView(R.id.tv_forget)
    TextView tvForget;
    @BindView(R.id.password)
    LinearLayout password;
    @BindView(R.id.btn_login)
    AppCompatButton btnLogin;
    @BindView(R.id.btn_register)
    AppCompatButton btnRegister;
    @BindView(R.id.tv_privacy)
    TextView tvPrivacy;
    @BindView(R.id.rv_password_login)
    RelativeLayout rvPasswordLogin;
    @BindView(R.id.input_verification_code)
    EditText inputVerificationCode;
    @BindView(R.id.tv_bd_code)
    TextView tvBdCode;
    @BindView(R.id.rv_vercode_login)
    RelativeLayout rvVercodeLogin;
    boolean isPasswordlogin = true;
    @BindView(R.id.tv_no_login)
    TextView tvNoLogin;
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;
    private MyCountDownTimer mcdt;
    private int fromType;
    public static final int REQUEST_CODE = 111;
    private Gson mGson = new Gson();

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        fromType = getIntent().getIntExtra(Contants.toLogin, 0);
        ButterKnife.bind(this);
        initview();
        setDarkStatusWhite(true);
        initlistener();
        checkPermission();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean checkPermission() {

        List<String> permissions = new ArrayList<>();
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(MyApplication.getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(MyApplication.getContext(), Manifest.permission.CAMERA)) {
            permissions.add(Manifest.permission.CAMERA);
        }

        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(MyApplication.getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(MyApplication.getContext(), Manifest.permission.ACCESS_FINE_LOCATION)) {
            permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(MyApplication.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION)) {
            permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }

        int len = permissions.size();
        if (len != 0) {
            String[] per = new String[len];
            for (int i = 0; i < len; i++) {
                per[i] = permissions.get(i);
            }
            requestPermissions(
                    per,
                    REQUEST_CODE);
            return false;
        }
        return true;

    }

    private void initview() {

        String mobile = SpUtils.getString(Contants.userName);
        String password = SpUtils.getString(Contants.Password);
        isPasswordlogin = SpUtils.getBoolean(Contants.isPasswordlogin, true);
        Log.d(TAG, "是否是密码登录" + isPasswordlogin);
        if (isPasswordlogin) {
            tvSwitchLogin.setText("验证码登录");
            rvPasswordLogin.setVisibility(View.VISIBLE);
            rvVercodeLogin.setVisibility(View.GONE);
        } else {
            tvSwitchLogin.setText("密码登录");
            rvPasswordLogin.setVisibility(View.GONE);
            rvVercodeLogin.setVisibility(View.VISIBLE);
        }
        inputPassword.setText(password);
        inputUser.setText(mobile);

    }

    private void initlistener() {
        tvSwitchLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPasswordlogin) {
                    isPasswordlogin = false;
                    tvSwitchLogin.setText("密码登录");
                    rvPasswordLogin.setVisibility(View.GONE);
                    rvVercodeLogin.setVisibility(View.VISIBLE);
                } else {
                    isPasswordlogin = true;
                    tvSwitchLogin.setText("验证码登录");
                    rvPasswordLogin.setVisibility(View.VISIBLE);
                    rvVercodeLogin.setVisibility(View.GONE);
                }

            }
        });
        CheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //如果选中，显示密码
                    inputPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    //否则隐藏密码
                    inputPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                inputPassword.setSelection(inputPassword.length());//将光标移至文字末尾
            }
        });
        tvBdCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mcdt = new MyCountDownTimer(tvBdCode, 60000, 1000);
                requestCode();

            }
        });
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "是否是密码登录2" + isPasswordlogin);
                if (isNullPwd()) {
                    if (isPasswordlogin) { //密码登录
                        if (TextUtils.isEmpty(inputPassword.getText().toString())) {
                            ToastUtil.setToast("密码不能为空");
                            return;
                        }

                        Map<String, String> headers = new HashMap<>();
                        headers.put("Access-Client", "OrgApp");
                        headers.put("Access-RegistrationId", JPushInterface.getRegistrationID(MyApplication.getContext()));
                        headers.put("Access-Platform", "Android");
                        NetServices.Factory.getService().login(headers,
                                inputUser.getText().toString(), inputPassword.getText().toString(), "2"
                        ).subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new BaseComPleteObserver<Login>(LoginActivity.this) {
                                    @Override
                                    protected void onSuccees(BaseEntity<Login> t) throws Exception {
                                        Log.d(TAG, t.toString());
                                        MyApplication.LoginEntity = t.getData();
                                        if (t.getData() != null) {

                                            SpUtils.put(Contants.userName, StrUtil.getString(inputUser));
                                            SpUtils.put(Contants.Password, inputPassword.getText().toString());
                                            SpUtils.put(Contants.isPasswordlogin, true);
                                            SpUtils.put(Contants.Token, MyApplication.LoginEntity.getToken());
                                            SpUtils.put(Contants.Id, MyApplication.LoginEntity.getUser().getDoctorId());
                                            String logininfo = new Gson().toJson(t.getData());
                                            SpUtils.put(Contants.LoginInfo, logininfo);
                                            SpUtils.put(Contants.logoOut, false);
                                            RetrofitFactory.setToken(MyApplication.LoginEntity.getToken());
                                            String loginjson = new Gson().toJson(t);
                                            LoginEntity loginEntity = new Gson().fromJson(loginjson, LoginEntity.class);
                                            PrescriptionMessageEntity prescriptionMessageEntity = new PrescriptionMessageEntity();
                                            prescriptionMessageEntity.setDoctor(loginEntity);
                                            String loginJson = mGson.toJson(prescriptionMessageEntity);
                                            myShared(loginJson);

                                            MyApplication.isLogin = true;
                                            if (fromType == Contants.From_mainActivity) {
                                                RxBus.get().post(Event.Login_success, true);
                                                finish();
                                            } else if (fromType == Contants.From_WEB_Activity) {
                                                RxBus.get().post(Event.Login_success, true);
                                                Intent intent = new Intent();
                                                intent.putExtra("loginJSON",loginJson);
                                                setResult(RESULT_OK, intent);
                                                finish();
                                            } else {
                                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                                startActivity(intent);
                                                finish();
                                            }
                                        }
                                    }

                                });
                    } else {
                        if (TextUtils.isEmpty(inputVerificationCode.getText().toString())) {
                            ToastUtil.setToast("验证码不能为空");
                            return;
                        }
                        Map<String, String> headers = new HashMap<>();
                        headers.put("Access-Client", "OrgApp");
                        headers.put("Access-RegistrationId", JPushInterface.getRegistrationID(MyApplication.getContext()));
                        headers.put("Access-Platform", "Android");
                        NetServices.Factory.getService().login(headers,
                                inputUser.getText().toString(), inputVerificationCode.getText().toString(), "1"
                        ).subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new BaseComPleteObserver<Login>(LoginActivity.this) {
                                    @Override
                                    protected void onSuccees(BaseEntity<Login> t) throws Exception {

                                        Log.d(TAG, t.toString());
                                        Log.d(TAG, t.toString());
                                        MyApplication.LoginEntity = t.getData();
                                        if (t.getData() != null) {
                                            SpUtils.put(Contants.userName, StrUtil.getString(inputUser));
                                            SpUtils.put(Contants.isPasswordlogin, false);
                                            SpUtils.put(Contants.Token, MyApplication.LoginEntity.getToken());
                                            SpUtils.put(Contants.Id, MyApplication.LoginEntity.getUser().getDoctorId());
                                            String logininfo = new Gson().toJson(t.getData());
                                            SpUtils.put(Contants.LoginInfo, logininfo);
                                            SpUtils.put(Contants.logoOut, false);
                                            RetrofitFactory.setToken(MyApplication.LoginEntity.getToken());
                                            String loginjson = new Gson().toJson(t);
                                            LoginEntity loginEntity = new Gson().fromJson(loginjson, LoginEntity.class);
                                            PrescriptionMessageEntity prescriptionMessageEntity = new PrescriptionMessageEntity();
                                            prescriptionMessageEntity.setDoctor(loginEntity);
                                            String loginJson = mGson.toJson(prescriptionMessageEntity);
                                            myShared(loginJson);

                                            MyApplication.isLogin = true;
                                            if (fromType == Contants.From_mainActivity) {
                                                RxBus.get().post(Event.Login_success, true);
                                                finish();
                                            } else if (fromType == Contants.From_WEB_Activity) {
                                                RxBus.get().post(Event.Login_success, true);
                                                Intent intent = new Intent();
                                                intent.putExtra("loginJSON",loginJson);
                                                setResult(RESULT_OK, intent);
                                                finish();
                                            } else {
                                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                                startActivity(intent);
                                                finish();
                                            }

                                        }

                                    }

                                });
                    }

                }
            }
        });

        tvNoLogin.setOnClickListener(new View.OnClickListener() { //暂时不登录直接进入首页
            @Override
            public void onClick(View v) {
                if(fromType == Contants.From_WEB_Activity){
                    finish();
                }else {
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    MyApplication.isLogin = false;
                    MyApplication.LoginEntity = null;
                    SpUtils.put(Contants.LoginJson, "");
                    startActivity(intent);
                    finish();
                }

            }
        });

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, ChooseRegisterActivity.class);
                startActivity(intent);
            }
        });

        tvForget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, ChangePasswordActivity.class);
                startActivity(intent);
            }
        });

        tvPrivacy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent Privacy = new Intent(LoginActivity.this, PrivacyActivity.class);
                startActivity(Privacy);
            }
        });

        tvAgreement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(LoginActivity.this,AgreementActivity.class);
                startActivity(intent);
            }
        });
    }

    private boolean isNullPwd() {
        if (TextUtils.isEmpty(StrUtil.getString(inputUser))) {
            ToastUtil.setToast(getResources().getString(R.string.enter_mobile_empty));
            return false;
        }
        if (!StrUtil.isMobile(StrUtil.getString(inputUser))) {
            ToastUtil.setToast(getResources().getString(R.string.mobile_empty));
            return false;
        }

        return true;
    }

    private void requestCode() {
        if (!StrUtil.isMobile(StrUtil.getString(inputUser))) {
            ToastUtil.setToast("手机号码格式不正确");
        } else {
            NetServices.Factory.getService().SendMobileCode(StrUtil.getString(inputUser)
            ).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseComPleteObserver(LoginActivity.this) {
                        @Override
                        protected void onSuccees(BaseEntity t) throws Exception {
                            LogUtils.d(TAG, t.toString());
                            if (t.getCode() == 0) {
                                mcdt.start();
                            }
                            ToastUtil.setToast("发送成功");
                        }
                    });
        }
    }

    private void codeLogin() {


    }

    private void passwordLogin() {

    }

    /**
     * 本地保存
     *
     * @param
     */
    private void myShared(String loginJson) {

        SpUtils.put(Contants.LoginJson, loginJson);
        Log.d("login", "id=" + loginJson);

    }

}
